
// <copyright file="OpCodeLookupHelper.cs" company="Subhadra Software Solutions">
//   
// </copyright>
// <summary>
//   The op code lookup helper.
// </summary>

namespace SubhadraSolutions.Sharp.Utils.Reflection.CodeSerialization
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Reflection.Emit;

    /// <summary>
    /// The op code lookup helper.
    /// </summary>
    internal static class OpCodeLookupHelper
    {
        #region Static Fields

        /// <summary>
        /// The op codes dictionary.
        /// </summary>
        private static readonly Dictionary<short, OpCode> _opCodesDictionary;

        #endregion Static Fields

        #region Constructors and Finalizers

        /// <summary>
        /// Initializes static members of the <see cref="OpCodeLookupHelper"/> class.
        /// </summary>
        static OpCodeLookupHelper()
        {
            FieldInfo[] fields = typeof(OpCodes).GetFields(BindingFlags.Static | BindingFlags.Public);
            _opCodesDictionary = fields.Select(field => (OpCode)field.GetValue(null)).ToDictionary(code => code.Value);
        }

        #endregion Constructors and Finalizers

        #region Methods

        /// <summary>
        /// The get op code by value.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <returns>
        /// The <see cref="OpCode"/>.
        /// </returns>
        internal static OpCode GetOpCodeByValue(short value)
        {
            return _opCodesDictionary[value];
        }

        /// <summary>
        /// The try get op code by value.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="code">
        /// The code.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        internal static bool TryGetOpCodeByValue(short value, out OpCode code)
        {
            return _opCodesDictionary.TryGetValue(value, out code);
        }

        #endregion Methods
    }
}
